package com.bkitmobile.kesu.android.GUI;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import com.bkitmobile.kesu.android.ClassInfo.ImageAdapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public abstract class SearchImageDialog extends Dialog implements OnItemClickListener{
	private static final File path = Environment.getExternalStorageDirectory();
	public SearchImageDialog(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		 setContentView(R.layout.grid_search_img);
		 GridView gridview = (GridView) findViewById(R.id.gridview);
		 List<File> listFile = getFiles(path);
		 List<Bitmap> listBitmap = new LinkedList<Bitmap>();
		
		 for (File f:listFile){
			 try {
				 BitmapDrawable bm = new BitmapDrawable(f.getPath());
				 if (bm.getBitmap() != null) {
					 listBitmap.add(resize(bm.getBitmap()));
				 }
			 } catch (Exception e){
				 
			 }
		 }
		 Log.d("number of file", listFile.size()+"");
		 if (listBitmap.size() == 0) return;
		 gridview.setAdapter(new ImageAdapter(getContext(),listBitmap));
		 gridview.setOnItemClickListener(this);
	}
	private List<File> getFiles(File path){
		List<File> listFile = new LinkedList<File>();
		File[] lsF = path.listFiles();
		System.out.println(path.toString());
		if (lsF == null) return listFile;
		for (int i = 0 ; i <lsF.length ; i++){
			if (lsF[i].isFile()){
				listFile.add(lsF[i]);
				Log.d("path1", lsF[i].getPath());
			} else {
				List<File> listSub = getFiles(lsF[i]);
				for (File f : listSub){
					listFile.add(f);
				}
			}
		}
		return listFile;
	}
	public abstract void setImage(Bitmap img);
	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
		// TODO Auto-generated method stub
		Bitmap bm = (Bitmap) adapter.getItemAtPosition(position);
		setImage(bm);
		dismiss();
	}
	private Bitmap resize(Bitmap bm){
		//new width / heigth
		int newWidth = 150;
		int newHeight = 150;
		// create a matrix for the manipulation
		// resize the bit map
		// recreate the new Bitmap and set it back
		Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm,newWidth, newHeight,false);
		return resizedBitmap;
	}
}
